package com.wang.mvchain.stat.service.implay;

import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wang.mvchain.common.service.BaseServiceImplay;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.HtmlParserUtil;
import com.wang.mvchain.common.util.PageInfoUtil;
import com.wang.mvchain.finan.service.IFinanService;
import com.wang.mvchain.outer.util.TradeUtil;
import com.wang.mvchain.stat.dao.IAStatTaskDAO;
import com.wang.mvchain.stat.pojo.AStatTask;
import com.wang.mvchain.stat.pojo.AStatTaskEnum;
import com.wang.mvchain.stat.service.IStatService;
import com.wang.mvchain.system.pojo.ACoinrate;
import com.wang.mvchain.system.service.IWebsiteService;
import com.wang.mvchain.users.pojo.AUsersTaskEnum;
import com.wang.mvchain.users.service.IOrdersService;
import com.wang.mvchain.users.service.IUsersService;

/**
 * 统计的所有服务类
 * @author wangsh
 *
 */
@Service("statService")
public class StatServiceImplay extends BaseServiceImplay implements IStatService
{
	@Resource
	private IAStatTaskDAO statTaskDAO;
	
	@Resource
	private IUsersService usersService;
	@Resource
	private IOrdersService ordersService;
	@Resource
	private IWebsiteService websiteService;
	@Resource
	private IFinanService finanService ;
	
	/**
	 * 添加一个用户任务统计
	 */
	@Override
	public JSONObject insertOneStatTaskService(AStatTask statTask)
	{
		JSONObject resultJSON = new JSONObject();
		
		/*//先判断用户id和日期是否存在
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("usersid", statTask.getUsersid() + "");
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(statTask.getCurrdate());
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		
		//查询当天是否统计过
		Date currSt = calendar.getTime() ; 
		calendar.add(Calendar.DATE, 1);
		Date currEd = calendar.getTime() ; 
		condMap.put("currSt", this.dateUtil.formatDateTime(currSt));
		condMap.put("currEd", this.dateUtil.formatDateTime(currEd));
		//删除当天的统计记录
		this.deleteBatchStatTaskService(condMap);*/
		
		int res = this.statTaskDAO.save(statTask);
		if (res > 0)
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "添加成功");
		} else
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "添加失败");
		}
		return resultJSON;
	}

	/**
	 * 更新一个用户任务统计
	 */
	@Override
	public JSONObject updateOneStatTaskService(AStatTask statTask)
	{
		JSONObject resultJSON = new JSONObject();

		int res = this.statTaskDAO.update(statTask);
		if (res > 0)
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "更新成功");
		} else
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "更新失败");
		}
		return resultJSON;
	}

	/**
	 * 删除一个用户任务统计
	 */
	@Override
	public JSONObject deleteOneStatTaskService(AStatTask statTask)
	{
		JSONObject resultJSON = new JSONObject();
		int res = this.statTaskDAO.delete(statTask);
		if (res > 0)
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "删除成功");
		} else
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}
	
	/**
	 * 删除一个用户任务统计
	 */
	@Override
	public JSONObject deleteBatchStatTaskService(Map<String, Object> map)
	{
		JSONObject resultJSON = new JSONObject();
		if(map.size() == 0 )
		{
			resultJSON.put("code", "-1");
			resultJSON.put("info", "条件为空");
			return resultJSON ; 
		}
		int res = this.statTaskDAO.deleteCond(map);
		if (res > 0)
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "删除成功");
		} else
		{
			resultJSON.put("code", res + "");
			resultJSON.put("info", "删除失败");
		}
		return resultJSON;
	}

	/**
	 * 查询一个用户任务统计
	 */
	@Override
	public AStatTask findOneStatTaskService(Map<String, Object> condMap)
	{
		AStatTask statTask =  this.statTaskDAO.findOne(condMap);
		return statTask ; 
	}

	/**
	 * 查询多个用户任务统计
	 */
	@Override
	public List<AStatTask> findCondListStatTaskService(PageInfoUtil pageInfoUtil,
			Map<String, Object> condMap)
	{
		List<AStatTask> statTaskList = Collections.emptyList() ; 
		if(pageInfoUtil != null)
		{
			//分页查询数据
			Page<AStatTask> pageInfo = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			statTaskList = this.statTaskDAO.findList(condMap);
			//设置总记录数
			pageInfoUtil.setTotalRecord(Long.valueOf(pageInfo.getTotal()).intValue());
		}else
		{
			statTaskList = this.statTaskDAO.findList(condMap);
		}
		return statTaskList ; 
	}

	@Override
	public AStatTask updateStatTaskService(Date currDate)
	{
		/* 新创建出来的对象 */
		AStatTask statTask = null;
		
		Calendar now = Calendar.getInstance();
		now.setTime(currDate);
		now.set(Calendar.HOUR_OF_DAY, 0);
		now.set(Calendar.MINUTE, 0);
		now.set(Calendar.SECOND, 0);
		Date stDate = now.getTime();
		now.add(Calendar.DATE, 1);
		Date edDate = now.getTime() ; 
		
		Map<String, Object> condMap = new HashMap<String, Object>();
		
		//查询美元汇率
		double usdRate = 1 ; 
		HtmlParserUtil htmlParserUtil = new HtmlParserUtil() ; 
		JSONObject resultJSON = htmlParserUtil.findCoinrateRate(new JSONObject());
		/* 键为币种的id */
		JSONObject usdJSON = (JSONObject) resultJSON.get("1");
		if(usdJSON != null)
		{
			usdRate = usdJSON.getDoubleValue("rate");
		}
		
		condMap.clear();
		condMap.put("st", this.dateUtil.formatDateTime(stDate));
		condMap.put("ed", this.dateUtil.formatDateTime(edDate));
		//必须是计算收益完成
		//condMap.put("status", "3");
		List<String> statusList = new ArrayList<String>();
		/* 统计的时候将计算收益和人工调整 都要计算的收益中
		 *  */
		statusList.add(AUsersTaskEnum.STATUS_CALINCOME.getStatus() + "");
		statusList.add(AUsersTaskEnum.STATUS_MANUADJ.getStatus() + "");
		condMap.put("statusList", statusList);
		condMap.put("orderby", "1");
		
		PageInfoUtil pageInfo = new PageInfoUtil();
		pageInfo.setPageSize(1000);
		List<Map> usersTaskMap = this.ordersService.findStatMapUsersTaskService(pageInfo,condMap);
		ConstatFinalUtil.SYS_LOG.info("---- 手动计算用户任务统计 ----总条数:" + pageInfo.getTotalRecord() + ",总页数:" + pageInfo.getTotalPage());
		for (int i = 1; i <= pageInfo.getTotalPage(); i++)
		{
			pageInfo.setCurrentPage(i);
			usersTaskMap = this.ordersService.findStatMapUsersTaskService(pageInfo,condMap);
			for (Iterator iterator = usersTaskMap.iterator(); iterator
					.hasNext();)
			{
				Map rowMap = (Map) iterator.next();
				
				boolean insertFlag = true ; 
				
				/* 
				 * 一天只能有一条任务统计信息
				 *  */
				/* 根据用户Id和时间开始和结束;查询用户的相关信息 */
				//先判断用户id和日期是否存在
				condMap.clear();
				condMap.put("usersid", rowMap.get("usersid") + "");
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(currDate);
				calendar.set(Calendar.HOUR_OF_DAY, 0);
				calendar.set(Calendar.MINUTE, 0);
				calendar.set(Calendar.SECOND, 0);
				calendar.set(Calendar.MILLISECOND, 0);
				
				//查询当天是否统计过
				Date currSt = calendar.getTime() ; 
				calendar.add(Calendar.DATE, 1);
				Date currEd = calendar.getTime() ; 
				condMap.put("currSt", this.dateUtil.formatDateTime(currSt));
				condMap.put("currEd", this.dateUtil.formatDateTime(currEd));
				List<AStatTask> statTaskList = this.findCondListStatTaskService(new PageInfoUtil(), condMap);
				if(statTaskList.size() > 0 )
				{
					statTask = statTaskList.get(0);
					insertFlag = false ; 
				}
				/* 为创建时间赋值 */
				if(statTask == null)
				{
					statTask = new AStatTask() ; 
					statTask.setCreatetime(new Date());
				}
				statTask.setUsersid(Integer.valueOf(rowMap.get("usersid") + ""));
				/* 订单的状态为默认为启用 */
				statTask.setStatus(AStatTaskEnum.STATUS_ENABLE.getStatus());
				
				//默认固定为cny
				statTask.setPriftcoinid(3);
				statTask.setCurrdate(currDate);
				statTask.setPrift(Double.valueOf(rowMap.get("totalprift") + ""));
				statTask.setFee(Double.valueOf(rowMap.get("totalpriftfee") + ""));
				statTask.setBuypricemax(Double.valueOf(rowMap.get("buypricemax") + ""));
				statTask.setBuypricemin(Double.valueOf(rowMap.get("buypricemin") + ""));
				statTask.setSellpricemax(Double.valueOf(rowMap.get("sellpricemax") + ""));
				statTask.setSellpricemin(Double.valueOf(rowMap.get("sellpricemin") + ""));
				statTask.setTaskcount(Integer.valueOf(rowMap.get("taskcount") + ""));
				statTask.setUpdatetime(new Date());
				
				/* 只有在添加的时候,才会更新余额 */
				//查询当时的用户余额情况
				condMap.clear();
				condMap.put("usersid", statTask.getUsersid()) ;
				condMap.put("status", "1") ;
				condMap.put("groupby", "1");
				List accountList = this.usersService.findUsersAccountStatListService(null , condMap);
				
				double totalBalance = 0 ; 
				//组建余额对象
				JSONObject balanceJSON = statTask.getBalanceJSON();
				for (Iterator iterator2 = accountList.iterator(); iterator2
						.hasNext();)
				{
					Map map = (Map) iterator2.next();
					JSONObject balanceTempJSON = new JSONObject();
					ACoinrate coinrate = (ACoinrate) map.get("coinrate") ; 
					//币种id
					balanceTempJSON.put("id", map.get("coinid") + "");
					if(coinrate != null)
					{
						balanceTempJSON.put("name", coinrate.getName() + "");
					}else
					{
						balanceTempJSON.put("name", "");
					}
					balanceTempJSON.put("balance", map.get("balance") + "");
					balanceTempJSON.put("fundmoney", map.get("fundmoney") + "");
					//默认美元
					double cny = 0;
					if((TradeUtil.CNY_COINID + "").equalsIgnoreCase(map.get("coinid") + ""))
					{
						cny = Double.valueOf(map.get("balance") + ""); 
					}else if((TradeUtil.USD_COINID + "").equalsIgnoreCase(map.get("coinid") + ""))
					{
						cny = Double.valueOf(map.get("balance") + "") * usdRate ; 
					}
					balanceTempJSON.put("cny", doubleOperUtil.round(cny, 5, RoundingMode.DOWN.ordinal()) + "");
					
					
					totalBalance += cny ; 
					
					balanceJSON.put("coinid_" + map.get("coinid") + "", balanceTempJSON);
					
					balanceJSON.put("total_cny_balance", doubleOperUtil.round(totalBalance, 5, RoundingMode.DOWN.ordinal()) + "");
				}
				statTask.setBalance(balanceJSON + "");
				
				//仅存储大于0的订单,当天的订单统计也存储
				if(statTask.getTaskcount() > 0 || 
						statTask.getCreatetime().getTime() - statTask.getCurrdate().getTime() < ConstatFinalUtil.SECOND * 60 * 60 * 23)
				{
					JSONObject resDBJSON = new JSONObject() ; 
					if(insertFlag)
					{
						resDBJSON = this.insertOneStatTaskService(statTask);
					}else
					{
						resDBJSON = this.updateOneStatTaskService(statTask);
					}
					ConstatFinalUtil.SYS_LOG.info("--手动计算用户任务统计-- 存储结果:{}",resDBJSON);
				}
			}
			
			ConstatFinalUtil.SYS_LOG.info("---- 手动计算用户任务统计 ----总条数:" + pageInfo.getTotalRecord() + ",总页数:" + pageInfo.getTotalPage()
					+ ",当前页:" + pageInfo.getCurrentPage());
		}
		ConstatFinalUtil.SYS_LOG.info("---- 手动计算用户任务统计完成 ----日期:" + currDate.toLocaleString());
		return statTask ; 
	}

}
